package com.shuaiche.yeguan.ui.upload;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.shuaiche.yeguan.R;
import com.shuaiche.yeguan.config.HttpUrl;
import com.shuaiche.yeguan.config.SCAppConfig;
import com.shuaiche.yeguan.model.SCAccessAuthResponse;
import com.shuaiche.yeguan.model.SCCarPicsModel;
import com.shuaiche.yeguan.net.http.HttpCallBack;
import com.shuaiche.yeguan.net.http.HttpHelper;
import com.shuaiche.yeguan.net.oss.MultiImagesUploadManager;
import com.shuaiche.yeguan.util.DeviceHelper;
import com.shuaiche.yeguan.util.GlideUtil;
import com.shuaiche.yeguan.util.ToastShowUtils;
import com.shuaiche.yeguan.views.dialog.LoadingDialog;
import com.shuaiche.yeguan.views.dialog.PermissionDialog;
import com.shuaiche.yeguan.views.photopicker.PhotoPickerActivity;
import com.shuaiche.yeguan.views.photopicker.SelectModel;
import com.shuaiche.yeguan.views.photopicker.intent.PhotoPickerIntent;

import java.util.ArrayList;
import java.util.List;

/**
 * 上传图片-证件资料
 */
public class DocumentFragment extends Fragment implements View.OnClickListener {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private ImageView iv_driving_license_1;
    private ImageView iv_driving_license_2;
    private ImageView iv_id_front;
    private ImageView iv_id_back;

    private RecyclerView rv_regist_cert;
    private RecyclerView rv_other_pics;
    private ImageButton btn_delete_license_1;
    private ImageButton btn_delete_license_2;
    private ImageButton btn_delete_id_1;
    private ImageButton btn_delete_id_2;
    private ActivityResultLauncher<Intent> photoResultLauncher;
    private int uploadPicType = 0;//0 行驶证正页 1行驶证副页 2车辆登记证 3身份证正面 4身份证反面 5其他证件照
    private LoadingDialog loadingDialog;

    /**
     * 需上传的图片
     */
    private ArrayList<String> picList = new ArrayList<>();

    private String drivingLicense1 = "";//行驶证正页
    private String drivingLicense2 = "";//行驶证副页
    private String idcardFront = "";//身份证正面
    private String idcardBack = "";//身份证反面

     private List<String> registCertList = new ArrayList<>();
    private CarPictureAdapter registCertAdapter;
    private static final int maxRegistCertTotal = 10;

    private List<String> othersList = new ArrayList<>();
    private CarPictureAdapter othersAdapter;
    private static final int maxOterTotal = 30;
    private ArrayList<SCCarPicsModel> certPicsList;

    public DocumentFragment() {
        // Required empty public constructor
    }
    public static DocumentFragment newInstance(ArrayList<SCCarPicsModel> certPicsList) {
        DocumentFragment fragment = new DocumentFragment();
        Bundle args = new Bundle();
        args.putSerializable("certList",certPicsList);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            certPicsList = (ArrayList<SCCarPicsModel>) getArguments().getSerializable("certList");

        }

        photoResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == Activity.RESULT_OK){
                            handlePhotoActivityResultData(result);
                        }
                    }
                });
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_document, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        loadingDialog = new LoadingDialog(getContext());
        iv_driving_license_1 = view.findViewById(R.id.iv_driving_license_1);
        iv_driving_license_2 = view.findViewById(R.id.iv_driving_license_2);
        btn_delete_license_1 = view.findViewById(R.id.btn_delete_license_1);
        btn_delete_license_2 = view.findViewById(R.id.btn_delete_license_2);
        iv_id_front = view.findViewById(R.id.iv_id_front);
        iv_id_back = view.findViewById(R.id.iv_id_back);
        btn_delete_id_1 = view.findViewById(R.id.btn_delete_id_1);
        btn_delete_id_2 = view.findViewById(R.id.btn_delete_id_2);
        rv_regist_cert = view.findViewById(R.id.rv_regist_cert);
        rv_other_pics = view.findViewById(R.id.rv_other_pics);

        iv_driving_license_1.setOnClickListener(this);
        iv_driving_license_2.setOnClickListener(this);
        btn_delete_license_1.setOnClickListener(this);
        btn_delete_license_2.setOnClickListener(this);
        iv_id_front.setOnClickListener(this);
        iv_id_back.setOnClickListener(this);
        btn_delete_id_1.setOnClickListener(this);
        btn_delete_id_2.setOnClickListener(this);

        int picWidth = DeviceHelper.getScreenWidthPx(getActivity())/4-20;
        ViewGroup.LayoutParams params = iv_driving_license_1.getLayoutParams();
        params.width = picWidth;
        params.height = picWidth;
        iv_driving_license_1.setLayoutParams(params);


        ViewGroup.LayoutParams params2 = iv_driving_license_2.getLayoutParams();
        params2.width = picWidth;
        params2.height = picWidth;
        iv_driving_license_2.setLayoutParams(params2);

        initPicList(certPicsList);

        initRegistCertRecyerView();
        initOthersRecyerView();
    }

    private void initPicList(ArrayList<SCCarPicsModel> certPicsList) {
        if (certPicsList == null || certPicsList.isEmpty()){
            registCertList.add(CarPictureAdapter.ADD_PIC);
            othersList.add(CarPictureAdapter.ADD_PIC);
            return;
        }

        for (SCCarPicsModel picModel : certPicsList) {
            if (SCAppConfig.CERT_PIC_CAR_LICENSE_FRONT.equals(picModel.getDescription())){//行驶证主页
                drivingLicense1 = picModel.getPicUrl();
                GlideUtil.loadImg(getContext(),drivingLicense1,iv_driving_license_1);
                btn_delete_license_1.setVisibility(View.VISIBLE);

            }else if (SCAppConfig.CERT_PIC_CAR_LICENSE_BACK.equals(picModel.getDescription())){//行驶证副页
                drivingLicense2 = picModel.getPicUrl();
                GlideUtil.loadImg(getContext(),drivingLicense2,iv_driving_license_2);
                btn_delete_license_2.setVisibility(View.VISIBLE);
            }else if (SCAppConfig.CERT_PIC_CAR_REG_BOOK.equals(picModel.getDescription())){//登记证
                registCertList.add(picModel.getPicUrl());
            }else if (SCAppConfig.CERT_PIC_ID_FRONT.equals(picModel.getDescription())){//身份证正面
                idcardFront = picModel.getPicUrl();
                GlideUtil.loadImg(getContext(),idcardFront,iv_id_front);
                btn_delete_id_1.setVisibility(View.VISIBLE);
            }else if (SCAppConfig.CERT_PIC_ID_BACK.equals(picModel.getDescription())){//身份证反面
                idcardBack = picModel.getPicUrl();
                GlideUtil.loadImg(getContext(),idcardBack,iv_id_back);
                btn_delete_id_2.setVisibility(View.VISIBLE);
            }else if (SCAppConfig.CERT_PIC_OTHER_CERT.equals(picModel.getDescription())){//其他
                othersList.add(picModel.getPicUrl());
            }
        }

        if (registCertList.size() < 10){
            registCertList.add(CarPictureAdapter.ADD_PIC);
        }

        if (othersList.size() < 30){
            othersList.add(CarPictureAdapter.ADD_PIC);
        }
    }

    private void initOthersRecyerView() {


        othersAdapter = new CarPictureAdapter(getContext(),othersList);
        othersAdapter.setOnItemClickListener(new CarPictureAdapter.OnItemClickListener() {
            @Override
            public void onDeleteClick(int position) {
                othersAdapter.removeItem(position);
            }

            @Override
            public void onItemClick(int position) {
                if (CarPictureAdapter.ADD_PIC.equals(othersList.get(position))){
                    uploadPicType = 5;
                    PhotoPickerIntent intent = new PhotoPickerIntent(getContext());
                    int canUpNum = maxOterTotal - (othersList.size()-1);
                    Log.e("canUpNum",canUpNum+"");
                    intent.setMaxTotal(canUpNum);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true);
                    photoResultLauncher.launch(intent);
                }else {
                    //预览图片

                }

            }
        });

        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 4);
        rv_other_pics.setLayoutManager(layoutManager);
        rv_other_pics.setAdapter(othersAdapter);
    }

    private void initRegistCertRecyerView() {



        registCertAdapter = new CarPictureAdapter(getContext(),registCertList);
        registCertAdapter.setOnItemClickListener(new CarPictureAdapter.OnItemClickListener() {
            @Override
            public void onDeleteClick(int position) {
                registCertAdapter.removeItem(position);
            }

            @Override
            public void onItemClick(int position) {
                if (CarPictureAdapter.ADD_PIC.equals(registCertList.get(position))){
                    uploadPicType = 2;
                    checkWriteReadPermission(1);

                }else {
                    //预览图片

                }

            }
        });

        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 4);
        rv_regist_cert.setLayoutManager(layoutManager);
        rv_regist_cert.setAdapter(registCertAdapter);

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_driving_license_1){
            uploadPicType = 0;
            checkWriteReadPermission(0);

        }else if (v.getId() == R.id.iv_driving_license_2){
            uploadPicType = 1;
            checkWriteReadPermission(0);
        }else if (v.getId() == R.id.btn_delete_license_1){
            drivingLicense1 = "";
            btn_delete_license_1.setVisibility(View.GONE);
            iv_driving_license_1.setImageResource(R.mipmap.addpic);
        }else if (v.getId() == R.id.btn_delete_license_1){
            drivingLicense2 = "";
            btn_delete_license_2.setVisibility(View.GONE);
            iv_driving_license_2.setImageResource(R.mipmap.addpic);
        }else if (v.getId() == R.id.iv_id_front){
            uploadPicType = 3;
            checkWriteReadPermission(0);
        }else if (v.getId() == R.id.iv_id_back){
            uploadPicType = 4;
            checkWriteReadPermission(0);
        }else if (v.getId() == R.id.btn_delete_id_1){
            idcardFront = "";
            btn_delete_id_1.setVisibility(View.GONE);
            iv_id_front.setImageResource(R.drawable.pic_auth_legal_positive);
        }else if (v.getId() == R.id.btn_delete_id_2){
            idcardBack = "";
            btn_delete_id_2.setVisibility(View.GONE);
            iv_id_back.setImageResource(R.drawable.pic_auth_legal_opposite);
        }
    }

    private void checkWriteReadPermission(int type){

        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            PermissionDialog dialog = new PermissionDialog(getContext(),"申请文件读写权限","获取文件读写权限，读取手机中的图片文件，供您选择上传图片");
            dialog.setOnPermissionResultListener(new PermissionDialog.OnPermissionResultListener() {
                @Override
                public void onConfirm() {
                    ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 10086);
                }

                @Override
                public void onRefuse() {

                }
            });
            dialog.setCancelable(false);
            dialog.show();
        }else {
            if (type == 0){
                startSingleSelectPhoto();
            }else {
                PhotoPickerIntent intent = new PhotoPickerIntent(getContext());
                int canUpNum = maxRegistCertTotal - (registCertList.size()-1);
                Log.e("canUpNum",canUpNum+"");
                intent.setMaxTotal(canUpNum);
                intent.setSelectModel(SelectModel.MULTI);
                intent.setShowCarema(true);
                photoResultLauncher.launch(intent);
            }
        }

    }

    private void startSingleSelectPhoto(){
        PhotoPickerIntent intent = new PhotoPickerIntent(getContext());
        intent.setMaxTotal(1);
        intent.setSelectModel(SelectModel.SINGLE);
        intent.setShowCarema(true);
        photoResultLauncher.launch(intent);
    }

    private void handlePhotoActivityResultData(ActivityResult result) {
        Intent data = result.getData();
        ArrayList<String> imagePaths = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);

        if (imagePaths != null && imagePaths.size() > 0) {
            picList = imagePaths;
            loadingDialog.show();
            getOssAuth();
        }
    }

    private void getOssAuth(){
        HttpHelper.getInstance().appendUrl(HttpUrl.OSS_AUTH)
                .get(new HttpCallBack<SCAccessAuthResponse>(getActivity()) {
                    @Override
                    public void onSuccessed(SCAccessAuthResponse result) {
                        SCAccessAuthResponse response = result.getData();
                        uploadPics(response);
                    }

                    @Override
                    public void onFailured(String errorCode, String errMsg) {
                        loadingDialog.dismiss();
                    }
                });
    }

    private void uploadPics(SCAccessAuthResponse auth){
        MultiImagesUploadManager.MultiImagesUploadCallback callback =
                new MultiImagesUploadManager.MultiImagesUploadCallback() {
                    @Override
                    public void onSuccess(List<PutObjectRequest> requests) {
                        if (loadingDialog != null){
                            loadingDialog.dismiss();
                        }
                        if (requests != null) {

                            if (uploadPicType == 0){//行驶证正页
                                drivingLicense1 ="/"+ requests.get(0).getObjectKey();
                                GlideUtil.loadImg(getContext(),drivingLicense1,iv_driving_license_1);
                                btn_delete_license_1.setVisibility(View.VISIBLE);
                            }else if (uploadPicType == 1){//行驶证副页
                                drivingLicense2 ="/"+ requests.get(0).getObjectKey();
                                GlideUtil.loadImg(getContext(),drivingLicense2,iv_driving_license_2);
                                btn_delete_license_2.setVisibility(View.VISIBLE);
                            }else if (uploadPicType == 2){//车辆登记证
                                registCertList.remove(registCertList.size() -1);

                                for (PutObjectRequest putObjectRequest: requests) {
                                    Log.e("uploadResult",SCAppConfig.IMG_URL + putObjectRequest.getObjectKey());
                                    registCertList.add("/"+ putObjectRequest.getObjectKey());
                                }

                                if (registCertList.size() < 10){
                                    registCertList.add(CarPictureAdapter.ADD_PIC);
                                }

                                if (registCertAdapter != null){
                                    registCertAdapter.notifyDataSetChanged();
                                }
                            }else if (uploadPicType == 3){
                                idcardFront ="/"+ requests.get(0).getObjectKey();
                                GlideUtil.loadImg(getContext(),idcardFront,iv_id_front);
                                btn_delete_id_1.setVisibility(View.VISIBLE);
                            }else if (uploadPicType == 4){
                                idcardBack ="/"+ requests.get(0).getObjectKey();
                                GlideUtil.loadImg(getContext(),idcardBack,iv_id_back);
                                btn_delete_id_2.setVisibility(View.VISIBLE);
                            }else if (uploadPicType == 5){//其他证件照
                                othersList.remove(othersList.size() -1);

                                for (PutObjectRequest putObjectRequest: requests) {
                                    Log.e("uploadResult",SCAppConfig.IMG_URL + putObjectRequest.getObjectKey());
                                    othersList.add("/"+ putObjectRequest.getObjectKey());
                                }

                                if (othersList.size() < maxOterTotal){
                                    othersList.add(CarPictureAdapter.ADD_PIC);
                                }

                                if (othersAdapter != null){
                                    othersAdapter.notifyDataSetChanged();
                                }
                            }


//                            for (PutObjectRequest putObjectRequest: requests) {
//                                Log.e("uploadResult", SCAppConfig.IMG_URL + putObjectRequest.getObjectKey());
//                                pictureList.add( putObjectRequest.getObjectKey());
//                            }


                        }

                    }

                    @Override
                    public void onFailure(List<PutObjectRequest> requests) {
                        if (loadingDialog != null){
                            loadingDialog.dismiss();
                        }
                        ToastShowUtils.showFailedToast("图片上传失败");
                    }
                };

        new MultiImagesUploadManager().startUpload(picList, callback,
                auth.getAccessKeyId(), auth.getAccessKeySecret(), auth.getSecurityToken(),
                SCAppConfig.OSS_CAR);
    }

    public List<SCCarPicsModel> getCertPics(){
        List<SCCarPicsModel> uploadList = new ArrayList<>();

        if (!TextUtils.isEmpty(drivingLicense1)){//行驶证正页
            SCCarPicsModel carPicsModel = new SCCarPicsModel();
            carPicsModel.setTitle(SCAppConfig.CERT_PIC);
            carPicsModel.setDescription(SCAppConfig.CERT_PIC_CAR_LICENSE_FRONT);
            String carPicUrl = drivingLicense1;
            carPicsModel.setPicUrl(carPicUrl);
            uploadList.add(carPicsModel);
        }

        if (!TextUtils.isEmpty(drivingLicense2)){//行驶证副页
            SCCarPicsModel carPicsModel = new SCCarPicsModel();
            carPicsModel.setTitle(SCAppConfig.CERT_PIC);
            carPicsModel.setDescription(SCAppConfig.CERT_PIC_CAR_LICENSE_BACK);
            String carPicUrl = drivingLicense2;
            carPicsModel.setPicUrl(carPicUrl);
            uploadList.add(carPicsModel);
        }

        //登记证
        for (String carPic : registCertList) {
            if (!CarPictureAdapter.ADD_PIC.equals(carPic)){
                SCCarPicsModel carPicsModel = new SCCarPicsModel();
                carPicsModel.setTitle(SCAppConfig.CERT_PIC);
                carPicsModel.setDescription(SCAppConfig.CERT_PIC_CAR_REG_BOOK);
                String carPicUrl = carPic;
                carPicsModel.setPicUrl(carPicUrl);
                uploadList.add(carPicsModel);
            }
        }

        if (!TextUtils.isEmpty(idcardFront)){//身份证正面
            SCCarPicsModel carPicsModel = new SCCarPicsModel();
            carPicsModel.setTitle(SCAppConfig.CERT_PIC);
            carPicsModel.setDescription(SCAppConfig.CERT_PIC_ID_FRONT);
            String carPicUrl = idcardFront;
            carPicsModel.setPicUrl(carPicUrl);
            uploadList.add(carPicsModel);
        }

        if (!TextUtils.isEmpty(idcardBack)){//身份证反面
            SCCarPicsModel carPicsModel = new SCCarPicsModel();
            carPicsModel.setTitle(SCAppConfig.CERT_PIC);
            carPicsModel.setDescription(SCAppConfig.CERT_PIC_ID_BACK);
            String carPicUrl = idcardBack;
            carPicsModel.setPicUrl(carPicUrl);
            uploadList.add(carPicsModel);
        }

        //其他证件照片
        for (String carPic : othersList) {
            if (!CarPictureAdapter.ADD_PIC.equals(carPic)){
                SCCarPicsModel carPicsModel = new SCCarPicsModel();
                carPicsModel.setTitle(SCAppConfig.CERT_PIC);
                carPicsModel.setDescription(SCAppConfig.CERT_PIC_OTHER_CERT);
                String carPicUrl = carPic;
                carPicsModel.setPicUrl(carPicUrl);
                uploadList.add(carPicsModel);
            }
        }

        return uploadList;
    }

}